package 基础语法;

import java.util.HashSet;

public class hashCode {
    public static void main(String[] args) {
        HashSet<MyClass> hashSet = new HashSet<>();
        hashSet.add(new MyClass(1));
        hashSet.add(new MyClass(2));// 会调用hashCode方法，将其返回值用于计算该对象在数组中的下标。可见，存不了基本数据类型，它们不是基础Object的
        System.out.println( hashSet.add(new MyClass(1)));//false,equals返回true且hashCode相同。就认为重复
        System.out.println(hashSet);//去看HashSet的某个父类AbstractCollection，其重写toString方法是使用迭代器便利的，还可以用增强for循环，forEach遍历

        System.out.println(hashSet.hashCode());// 看看
        testSpeed();
    }

    static void testSpeed() {
        HashSet<MyClassHashCode0> hashCode0s = new HashSet<>();

        int c = 100000;
        long start_1 = System.currentTimeMillis();

        for (int i = 0; i < c; i++) {
            hashCode0s.add(new MyClassHashCode0(false));

        }
        long end_1 = System.currentTimeMillis();
        System.out.println("默认hashCode()，用时：" + (end_1 - start_1) / 1000);

        HashSet<MyClassHashCode0> hashCode0s1 = new HashSet<>();

        start_1 = System.currentTimeMillis();

        for (int i = 0; i < c/3; i++) {
            hashCode0s1.add(new MyClassHashCode0(true));

        }
        end_1 = System.currentTimeMillis();
        System.out.println("hashCode()固定返回0，用时：" + (end_1 - start_1) / 1000);

    }
}

class MyClass {
    int code;

    MyClass(int code) {
        this.code = code;
    }

    @Override
    public int hashCode() {
        //System.out.println(code + "被调用");
        //int hashCode = super.hashCode();// Object的。基于对象地址值进行计算得到
        //System.out.println(hashCode);
        //return hashCode;
        return code;//
    }
    @Override
    public boolean equals(Object obj) {
        
        if( this.code==(((MyClass)obj).code)){
            return true;//只要code一样，就认为是一个对象，
        }
        return false;
    }
}

class MyClassHashCode0 {
    boolean return0;

    MyClassHashCode0(boolean code) {
        this.return0 = code;
    }

    @Override
    public int hashCode() {
        if (return0)
            return 0;
        return super.hashCode();
    }
}
